package com.easymin.weixin.common;

import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.crypto.hash.Sha1Hash;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * Created by shine on 16/1/8.
 */
public class WxUtils {
  
  /**
   * 构建MD5签名.
   */
  public static String buildMd5Sign(Map<String, Object> signParams) {

    Collection<String> keyset = signParams.keySet();
    List<String> list = new ArrayList<>(keyset);
    // 对key键值按字典升序排序
    Collections.sort(list);

    StringBuilder sb = new StringBuilder();
    for (String key : list) {
      sb.append(key).append("=").append(signParams.get(key));
      sb.append("&");
    }

    sb.setLength(sb.length() - 1);

    Md5Hash md5Hash = new Md5Hash(sb.toString());

    return md5Hash.toString();
  }

  /**
   * SHA1构建签名.
   */
  
  public static String buildSha1Sign(Map<String, Object> signParams) {

    Collection<String> keyset = signParams.keySet();
    List<String> list = new ArrayList<>(keyset);
    // 对key键值按字典升序排序
    Collections.sort(list);

    StringBuilder sb = new StringBuilder();
    for (String key : list) {
      sb.append(key).append("=").append(signParams.get(key));
      sb.append("&");
    }

    sb.setLength(sb.length() - 1);

    Sha1Hash sha1 = new Sha1Hash(sb.toString());

    return sha1.toString();
  }
}
